//
var _latestAppdemo = "";
// record current swap type wrapper id
var _currentSwapWrapper;
var _currentHistoryData;
var _lastNavIndex;
var _hTipTimeout;
var _appDemoRegExp = /appdemo_\d+\.\d+\.swf/i;
var _nodeDefault = {
    "app_height"  : 700, 
    "app_url"       : "%Gip_JS_Config.servers.asStaticServer%/client/1.0.0/appdemo_9.102952.swf", 
    "app_config"  : "",
    "gip_app_id"  : "",
    "gip_web_url" : "",
    "frame_url"    : ""
};
var _navs = ["Customization", "Source"];

init();

function init(){
    // Display tip when app setting is null
    if(location.search == "?is_first=1"){
       document.getElementById("fresh_man_tip").style.display="block"; 
    }
    // handler
    document.getElementById('delete_history_trigger').onclick = deleteHistory;
    document.getElementById('save_button').onclick = saveOptions;
    document.getElementById('save_as_button').onclick = saveAsOptions;
    document.getElementById('reset_button').onclick = resetOptions;
    //
    createNav();
    createConfigSelector();
    createSwapWrapper();
    checkLatestAppdemo();
    //注意：顺序不能弄反，必须先调用 renderHistory，然后在 restoreOptions
    // 因为在 renderHistory 中进行了 JSON 合法性校验
    renderHistory();
    restoreOptions();
}

function checkLatestAppdemo(){
    $.ajax({
        url: "http://gip-portal.happyelements.net/?method=GetAppXml&keyName=gameSwfUrl",
        type: "GET",
        dataType: "json"
        // data: args.data
        /*beforeSend: function ( xhr ) {
        xhr.overrideMimeType("text/plain; charset=x-user-defined");
        }*/
        }).done(function (data) {
            if(data && data["gameSwfUrl"]){
                _latestAppdemo = parseAppdemo(data["gameSwfUrl"]);
                if(_latestAppdemo != parseAppdemo($("#app_url").val())){
                    addGetAppdemoButton(parseAppdemo(_latestAppdemo));
                }
            }
    });
}

function parseAppdemo(url){
    url = url || "";
    //appdemo_9.75450
    // var start = url.indexOf("appdemo");
    // var end = url.indexOf(".swf");
    // return url.slice(start, end);
    return _appDemoRegExp.exec(url) ? _appDemoRegExp.exec(url)[0] : null;
}

function addGetAppdemoButton(version){
    var b = $("<b />").css("color", "red").text("Honey,Honey! A new " + version + " has been available!");
    //<input type="button" value="get the latest Appdemo" onClick="changeLatestAppdemo(this)" />
    var btn = $("<input />").attr({type:"button", value:"GET NOW!"}).click(changeLatestAppdemo);
    $("#option_get_latest").append(b, btn);
}

function changeLatestAppdemo(){
    var newUrl = $("#app_url").val().replace(_appDemoRegExp, _latestAppdemo);
    $("#app_url").val(newUrl);
    $("#option_get_latest input").remove();
    $("#option_get_latest b").remove();
}

// Saves options to localStorage.
function saveOptions() {
    var appData = {};
    for (var x in _nodeDefault) {
        appData[x]=document.getElementById(x).value;
    }
    var historyNode = document.getElementById("my_history");
    var historyName = historyNode.options[historyNode.selectedIndex].value;

    var oldHistoryData = {"Default":_nodeDefault};
    if(localStorage["history"]){
        oldHistoryData = JSON.parse(localStorage["history"]);
    }
    appData['swap_type'] = _currentSwapWrapper;

    oldHistoryData[historyName] = appData;
    localStorage["history"] = JSON.stringify(oldHistoryData);

    localStorage["config_name"] = historyName;

    // Update status to let user know options were saved.
    showTip("Options Saved.");
}

// Saves current options as a new config.
function saveAsOptions(){
    var historyName = prompt("Please input HISTORY NAME used to identify your current config:");
    if(historyName == null){
        return false;
    }
    if(historyName === ""){
        alert("History name can't be empty!");
        return false;
    }

    var oldHistoryData = {"Default":_nodeDefault};
    if(localStorage["history"]){
        oldHistoryData = JSON.parse(localStorage["history"]);
    }
    if(oldHistoryData[historyName]){
        if(!confirm("There has been a config named " + historyName + ".\n Are your sure to override it with your current config?")){
            return false;
        } 
    }
    var historyItem = {};
    for (var x in _nodeDefault) {
        historyItem[x]=document.getElementById(x).value;
    }
    historyItem['swap_type'] = _currentSwapWrapper;

    oldHistoryData[historyName] = historyItem;

    localStorage["config_name"] = historyName;
    localStorage["history"] = JSON.stringify(oldHistoryData);
    showTip("Saved.");
    renderHistory();
}

function deleteHistory(){
    var historyNode = document.getElementById("my_history");
    var index = historyNode.selectedIndex;
    var historyName = historyNode.options[index].value;
    if(localStorage['history'] === undefined || localStorage['history'] === "{}"){
        alert("There is nothing to be deleted!  Following is the default value.");
        return false;
    }
    if(!confirm("Are you sure to delete config data named "+historyName + "?")){
        return false;
    }
    var oldHistoryData = JSON.parse(localStorage["history"]);
    var length = 0;
    for(var key in oldHistoryData){
        length++;
    }
    if(length > 1){
        delete oldHistoryData[historyName];
        historyNode.removeChild(historyNode.options[index]);
        showTip("It has succeeded in deleting " + historyName);
    }else{
        showTip("Deleting " + historyName + " failed.", undefined, "red");
    }
    if(historyNode.options.length > 0){
        localStorage["config_name"] = historyNode.options[0].value;
    }
    localStorage["history"] = JSON.stringify(oldHistoryData);

    renderHistory();
    restoreOptions();
}

function createSwapWrapper(){
    var typeNodes = document.getElementsByName("swap_type");
    for(var i=0;i<typeNodes.length;i++){
        typeNodes[i].onclick = function(){
            restoreSwapStyle(this.value);
        }
    }
}

function createConfigSelector(){
    var historyNode = document.getElementById("my_history");
    historyNode.onchange = function(){
        var appData = JSON.parse(localStorage['history'])[this.value];
        for (var x in _nodeDefault) {
            var nodeId = x;
            document.getElementById(nodeId).value = appData[x];
        }
        localStorage["config_name"] = this.value;

        restoreSwapStyle(appData['swap_type'], appData['gip_app_id'], appData['gip_web_url'], appData['frame_url']);
        showTip("Config has been switched to "+this.value);
    }
}

function resetOptions() {
    for (var x in _nodeDefault) {
        document.getElementById(x).value = _nodeDefault[x];
    }
}

function showTip(txt, time, color){
    time = (typeof(time) == "undefined") ? 1500 : parseInt(time);
    if(txt){
        $("#operation_tip").html("<span>"+txt+"</span>");
    }else{
        $("#operation_tip").empty();
    }
    if(color){
        $("#operation_tip span").css("color", color);
    }
    clearTimeout(_hTipTimeout);
    if(time > 0){
        _hTipTimeout = setTimeout(function(){
            $("#operation_tip").empty();
        }, time);
    }
}

function renderHistory(){
    var data = {"Default" : _nodeDefault};
    if(localStorage['history'] && (localStorage['history'] !== "{}")){
        try{
            data = JSON.parse(localStorage['history']);
        }catch(e){
            localStorage['config_name'] = "Default";
            localStorage['history'] = JSON.stringify(data);
            showTip("Pasing JSON failed,It will use default data.Error:" + e, 0, "red");
        }
    }
    var node = document.getElementById("my_history");
    var historyName = localStorage["config_name"];
    if(data  && node){
        node.options.length = 0;
        for(var x in data){
            var option = new Option(x, x);
            node.appendChild(option);
            if(x == historyName){
                option.selected = true;
            }
        }
    }
}

// Restores state to saved value from localStorage.
function restoreOptions() {
    var historyName = localStorage["config_name"] || "Default";
    var data;
    try{
        data = JSON.parse(localStorage['history']);
    }catch(e){
        showTip("Pasing JSON failed,It will use default data.Error:" + e, 0, "red");
    }
    var appData = (data && data[historyName]) || _nodeDefault;
    for (var x in _nodeDefault) {
        var nodeVal = appData[x];
        //use default
        if(typeof(nodeVal) == "undefined"){
            nodeVal = _nodeDefault[x];
        }
        document.getElementById(x).value = nodeVal;
    }
    restoreSwapStyle(appData['swap_type'], appData['gip_app_id'], appData['gip_web_url'], appData['frame_url']);

}

function restoreSwapStyle(swapType, appId, webUrl, frameUrl){
    swapType = swapType || "1";
    document.getElementsByName("swap_type")[parseInt(swapType)-1].checked = true;
    var wrapperId = "swap_type_wrapper_" + swapType;

    if(_currentSwapWrapper){
        document.getElementById("swap_type_wrapper_" + _currentSwapWrapper).style.display = "none";
    }
    document.getElementById(wrapperId).style.display = "block";

    _currentSwapWrapper = swapType;

    if(appId){
        document.getElementById("gip_app_id").value = appId;
    }
    if(webUrl){
        document.getElementById("gip_web_url").value = webUrl;
    }
    if(frameUrl){
        document.getElementById("frame_url").value = frameUrl;
    }

}
function formatConfig(node){
    //node.value = js_beautify(node.value, {"indent_size":1, "indent_char":"\t"}); 
}

function createNav(){
    $("#content_nav li").click(function(e){
        if($(this).index() != _lastNavIndex){
            changeNav($(this).index());
            _lastNavIndex = $(this).index();
        }
    });
    //
    $("#save_source_button").click(function(e){
        if($("#history_source").val() != _currentHistoryData){
            _currentHistoryData = $("#history_source").val();
            var data;
            try{
                data = JSON.parse($("#history_source").val());
            }catch(e){
                showTip("The source you inputed was invaild!", 0, "red");
            }
            if(data){
                localStorage['history'] = JSON.stringify(data.history);
                localStorage['config_name'] = JSON.stringify(data.config_name);
                renderHistory();
                restoreOptions();
                //
                showTip("Saved.");
            }
        }
    });
    //default
    changeNav(0);
}

function changeNav(index){
    for(var i = 0; i < _navs.length; i++){
        $("#content_nav li").eq(i).html("<a>" + _navs[i] + "</a>");
        $("#content_nav li").eq(i).removeClass("selected");
        $("#content_box_" + i).hide();
    }
    $("#content_nav li").eq(index).empty();
    $("#content_nav li").eq(index).text(_navs[index]);
    $("#content_nav li").eq(index).addClass("selected");
    $("#content_box_" + index).show();
    switch(index){
        case 1:
            var data = {};
            if(localStorage['history'] && (localStorage['history'] !== "{}")){
                data.history = JSON.parse(localStorage['history'] || "{}");
            }
            data.config_name = localStorage["config_name"];
            _currentHistoryData = JSON.stringify(data);
            $("#history_source").val(_currentHistoryData);
            $("#history_source").select();
            break;
        case 0:
        default:
            showTip(null, 0);
    }
}
